#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct date
{
    int year;
    int month;
    int day;
} Date;

int checkisDate(int year, int month, int day)
{
    if (year < 1 || month < 1 || month > 12 || day < 1)
    {
        return 0;
    }
    return 1;
}

int compareDates(const void *a, const void *b)
{
    Date *dateA = *(Date **)a;
    Date *dateB = *(Date **)b;

    if (dateA->year != dateB->year)
    {
        return dateA->year - dateB->year;
    }

    if (dateA->month != dateB->month)
    {
        return dateA->month - dateB->month;
    }

    return dateA->day - dateB->day;
}

Date *inputDate()
{
    Date *date = (Date *)malloc(sizeof(Date));
    if (!date)
    {
        return NULL;
    }

    int valid = 0;
    while (!valid)
    {
        printf("请输入日期：(格式:XXXX YY ZZ): ");
        scanf("%d %d %d", &date->year, &date->month, &date->day);
        valid = checkisDate(date->year, date->month, date->day);
        if (!valid)
        {
            printf("日期输入不合法，请重新输入\n");

            while (getchar() != '\n')
                ;
        }
    }

    return date;
}

void sortDateP(Date *pdates[], int n)
{
    qsort(pdates, n, sizeof(Date *), compareDates);
}

void printDatesP(Date *pdates[], int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d-%02d-%02d ", pdates[i]->year, pdates[i]->month, pdates[i]->day);
    }
    printf("\n");
}

void freeDatesP(Date *pdates[], int n)
{
    for (int i = 0; i < n; i++)
    {
        free(pdates[i]);
    }
}

int main()
{
    int n = 3;
    Date *pdates[n];

    for (int i = 0; i < n; i++)
    {
        pdates[i] = inputDate();
    }

    printf("Before sorting:\n");
    printDatesP(pdates, n);

    sortDateP(pdates, n);

    printf("After sorting:\n");
    printDatesP(pdates, n);

    freeDatesP(pdates, n);

    return 0;
}